<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Model\User;
use App\Model\Order;
use App\Model\Product;
use App\Model\Position;
use App\Model\OrderShipment;
use App\Model\OrderProduct;
use App\Model\UserShipment;

use Illuminate\Support\Facades\Redis;
use App\Model\BistroIncomeDay;
use App\Model\BistroIncomeMonth;

use App\Model\ProductSaleDay;
use App\Model\ProductSaleMonth;

use App\Transformers\OrderTransformer;

use Illuminate\Support\Facades\DB;
use App\Service\UserService;

use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    //
    public function index(Request $request) {
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];

        $orders = Order::where('user_id', $user->id)->orderby('id', 'desc')->paginate(10);
        $data['data'] = [
            'orders' => $this->factalPaginator($orders, new OrderTransformer())
        ];
        return $this->apiSuccess($data);
    }

    public function addOrder(Request $request) {
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];
        $qr_code = $request->input('qr_code');
        $remarks = $request->input('remarks');
        $postion = Position::where('qr_code', $qr_code)->first();
        if(empty($postion)) return $this->apiError('找不到此位置');
        $exchange_list = $request->input('exchange_list');
        $product_list = [];
        $total_amount = 0;

        foreach ($exchange_list as $exc) {
            $tmp_product = [
                'product' => Product::findorfail($exc['product_id'])->toArray(),
                'num' => $exc['num']
            ];
            $total_amount = $total_amount * 1 + $tmp_product['product']['discount'] * $exc['num'];
            array_push($product_list, $tmp_product);
        }

        //查询序号 sort_number   需要每天清零
        $sort_number = Redis::get('bistro||'.$postion->bistro_id.'||sort_number');
        if(empty($sort_number)) {
            $sort_number = 1;
        }

        DB::beginTransaction();
        try {
            //订单
            $order = new Order();
            $order->user_id = $user->id;
//            $order->total_amount = $total_amount;
            $order->status = 'un_pay';
            $order->order_number = date('YmdHis').uniqid();
            $order->bistro_id = $postion->bistro_id;
            $order->position_id = $postion->id;
            $order->date = date('Y-m-d');
            $order->sort_number = $sort_number;
            if(!empty($remarks)) {
                $order->remarks = $remarks;
            }
            $order->save();
            //序号加一
            $sort_number += 1;
            Redis::set('bistro||'.$postion->bistro_id.'||sort_number', $sort_number);

            //插入订单商品
            foreach ($product_list as $product) {
                $order_product = new OrderProduct();
                $order_product->order_id = $order->id;
                $order_product->product_id = $product['product']['id'];
                $order_product->num = $product['num'];
                $order_product->total_amount = $product['product']['discount'] * $product['num'];
                $order_product->information = json_encode($product);
                $order_product->date = date('Y-m-d');
                $order_product->price = $product['product']['discount'];
                $order_product->save();
                //商品数量减少
                $product1 = Product::findorfail($product['product']['id']);
                $product1->save();
            }
//            if(!empty($shipment)) {//讲道理，暂时不需要
//                //插入订单地址
//                $order_shipment = new OrderShipment();
//                $order_shipment->order_id = $order->id;
//                $order_shipment->shipment_id = $shipment->id;
//                $order_shipment->shipment_detail = json_encode($shipment);
//                $order_shipment->user_detail = json_encode($user);
//                $order_shipment->save();
//            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->apiError($e->getMessage());
        }
        //删除购物车中商品
        $shopping_cart = User::getShoppingCart($user->id);
        $list = $shopping_cart['list'];
        foreach ($list as $key => $value) {
            foreach($product_list as $value2) {
                if($value2['product']['id'] == $value['product_id']) {
                    unset($list[$key]);
                }
            }
        }
        $total_num = 0;
        $arr_new_list = [];
        foreach ($list as $value2) {
            $total_num = $total_num * 1 + $value2['num'] * 1;
            array_push($arr_new_list, $value2);
        }
        //list 有了
        $json_list = json_encode($arr_new_list);
        User::updateShoppingCart($user->id, $json_list, $total_num);
        $data['data'] = [
            'order' => $order
        ];
        return $this->apiSuccess($data);
    }

    //订单支付
    public function payOrder(Request $request, $id) {
        //获取用户信息 身份验证
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];

        $order = Order::findorfail($id);
        $pay_amount = $order->total_amount * 1;
        $out_trade_no = uniqid().'|'.$id;
        //充值金额
        //小程序的app
        $app = app('wechat.payment');

        $result = $app->order->unify([
            'body' => '支付订单|'.$id,
            'out_trade_no' => $out_trade_no,
            'total_fee' => $pay_amount * 100,
//          'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => config('app.url') . '/api/payOrderCallBack', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI',
            'openid' => $user->openid,
            'attach' => '订单id||'.$id.'||支付金额'.$pay_amount
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $jssdk = $app->jssdk;
            $config = $jssdk->sdkConfig($result['prepay_id']); // 返回数组
            $data['data'] = [
                'config' => $config
            ];
//        //唤起输入密码信息
            return $this->apiSuccess($data);
        }
        //传入订单号
        //算出所需支付金额
    }

    //支付回调
    public function payOrderCallBack() {
        \Log::info('request arrived.');
        $wechat = app('wechat.payment');
        $response = $wechat->handlePaidNotify(function ($message, $fail) use ($wechat){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = $message['out_trade_no'];
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    \DB::transaction(function () use ($message){
                        \Log::info($message);
                        $whether_coupon = false;
                        $openid = $message['openid'];
                        $user = User::where('openid', $openid)->first();

                        $out_trade_no = $message['out_trade_no'];
                        $arr = explode('|', $out_trade_no);
                        $order_id = $arr[1];

                        //修改订单状态
                        $order = Order::findorfail($order_id);
                        $order->status = 'payed';
                        $order->save();


//                        $date = date('Y-m-d');
//                        $month = date('Y-m');
//                        $year = date('Y');


//                        //查询订单中商品 是否有代金金额 有 就添加用户代金金额
//                        $order_products = OrderProduct::where('order_id', $order_id)->get();
//                        foreach ($order_products as $op) {
//                            //product 减少库存
//                            $product = Product::findorfail($op->product_id);
////                            $product->storage = $product->storage * 1 - $op->num * 1;
//                            $product->sale_count = $product->sale_count * 1 + $op->num * 1;
//                            $product->save();
//
//                            //商品日销售
//                            $product_sale_day = ProductSaleDay::date($date)->productId($op->product_id)->first();
//                            if(empty($product_sale_day)) {
//                                $product_sale_day = new ProductSaleDay();
//                                $product_sale_day->product_id = $op->product_id;
//                                $product_sale_day->sale_count = 0;
//                                $product_sale_day->total_amount = 0;
//                                $product_sale_day->date = $date;
//                            }
//                            $product_sale_day->sale_count = $product_sale_day->sale_count * 1 + $op->num * 1;
//                            $product_sale_day->total_amount = $product_sale_day->total_amount * 1 + $op->total_amount * 1;
//                            $product_sale_day->save();
//
//                            //商品月销售
//                            $product_sale_month = ProductSaleMonth::month($month)->productId($op->product_id)->first();
//                            if(empty($product_sale_month)) {
//                                $product_sale_month = new ProductSaleMonth();
//                                $product_sale_month->product_id = $op->product_id;
//                                $product_sale_month->sale_count = 0;
//                                $product_sale_month->total_amount = 0;
//                                $product_sale_month->month = $month;
//                                $product_sale_month->year = $year;
//                            }
//                            $product_sale_month->sale_count = $product_sale_month->sale_count * 1 + $op->num * 1;
//                            $product_sale_month->total_amount = $product_sale_month->total_amount * 1 + $op->total_amount * 1;
//                            $product_sale_month->save();
//
//                        }

//                        //店铺日收益计算
//                        $bistro_income_day = BistroIncomeDay::date($date)->bistroId($order->bistro_id)->first();
//                        if(empty($bistro_income_day)) {
//                            $bistro_income_day = new BistroIncomeDay();
//                            $bistro_income_day->bistro_id = $order->bistro_id;
//                            $bistro_income_day->date = $date;
//                            $bistro_income_day->income = 0;
//                            $bistro_income_day->outcome = 0;
//                        }
//                        $bistro_income_day->income = $bistro_income_day->income * 1 + $message['total_fee']/100;
//                        $bistro_income_day->save();
//
//                        //店铺月收益计算
//                        $bistro_income_month = BistroIncomeMonth::month($month)->bistroId($order->bistro_id)->first();
//                        if(empty($bistro_income_month)) {
//                            $bistro_income_month = new BistroIncomeMonth();
//                            $bistro_income_month->bistro_id = $order->bistro_id;
//                            $bistro_income_month->month = $month;
//                            $bistro_income_month->year = $year;
//                            $bistro_income_month->income = 0;
//                            $bistro_income_month->outcome = 0;
//                        }
//                        $bistro_income_month->income = $bistro_income_month->income * 1 + $message['total_fee']/100;
//                        $bistro_income_month->save();

                    });
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
        return $response;
    }
}
